﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class NetConnectPage : EventManager
{
    public Image circleImg;                   // circle旋转动画
    public Text dotTex;                             //省略号旋转动画

    public override void InformationSetting()
    {
        StartCoroutine(CircleRotate(circleImg.GetComponent<Image>()));
        StartCoroutine(DotChangeText(0));
        SocketMgr.GetInstance().isNetOpen = false;
        StartConnectSever();
    }

    private void StartConnectSever()
    {
        if (Application.internetReachability == NetworkReachability.NotReachable)
        {
            TooL.ShowTipsPage("无法连接网络！请打开wifi或4G网络后重试。", TooL.TipsPageType.noCancelPage, () =>
            {
                StartConnectSever();
            });
        }
        else
        {
            StartCoroutine(ConnectSever());
        }
    }

    IEnumerator ConnectSever()
    {
        SocketMgr.GetInstance().InitNet();
        yield return new WaitUntil(() => SocketMgr.GetInstance().isNetOpen);
        CheckToken();
    }

    void CheckToken()
    {
        if (SocketMgr.GetInstance().isNetOpen)
        {
            string token = PlayerPrefs.GetString(DefaultKeyConst.VisitorTokenKey);
            if (!token.Equals(""))
            {
                string longitude = GameData.GetInstance().longitude;
                string latitude = GameData.GetInstance().latitude;

                MessageManager.GetInstance().SendMsg78("TOKEN", token, null, longitude, latitude);
            }
        }
        else
        {
            StartConnectSever();
        }
    }

    private string[] stringArr = { ". ", ". .", ". . ." };    //省略号变化显示
    IEnumerator DotChangeText(int index)
    {
        dotTex.text = stringArr[index];
        yield return new WaitForSeconds(0.5f);
        index++;
        if (index >= stringArr.Length) index = 0;
        StartCoroutine(DotChangeText(index));
    }

    private int[] rotation = { 0,-10,-20, -30,-40,-50, -60,-70,-80, -90,-100,-110 ,-120,-130,-140 ,-150,-160,-170, -180,       // circle旋转动画
        170,160,150,140,130, 120,110,100, 90,80,70, 60,50,40, 30,20,10 };
    IEnumerator CircleRotate(Image image)
    {
        int index = 0;
        int len = rotation.Length;
        while (true)
        {
            image.transform.localRotation = Quaternion.Euler(0, 0, rotation[index]);
            index++;
            if (index >= len)
            {
                index = 0;
            }
            yield return new WaitForSeconds(0.03f);
        }
    }



}
